<template>
<div>
  <!-- 设备类型新增表单 -->
  <equipment-category-form
    ref="categoryForm"
    :visible.sync="categoryFormVisible"
    @refreshDataList="handleCategoryAdded">
  </equipment-category-form>

  <!-- 生产厂家新增表单 -->
  <manufacturer-form
    ref="manufacturerForm"
    :visible.sync="manufacturerFormVisible"
    @refreshDataList="handleManufacturerAdded">
  </manufacturer-form>

  <!-- 设备品牌新增表单 -->
  <device-brand-form
    ref="brandForm"
    :visible.sync="brandFormVisible"
    @refreshDataList="handleBrandAdded">
  </device-brand-form>

  <!-- 设备型号新增表单 -->
  <equipment-model-form
    ref="modelForm"
    :visible.sync="modelFormVisible"
    @refreshDataList="handleModelAdded">
  </equipment-model-form>

  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="120px">
      <el-row  :gutter="15">
        <el-col :span="12">
            <el-form-item label="名称" prop="name"
                :rules="[
                 ]">
              <el-input v-model="inputForm.name" placeholder="请填写名称"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="设备编号" prop="code"
                :rules="[
                 ]">
              <el-input v-model="inputForm.code" placeholder="请填写设备编号"     ></el-input>
           </el-form-item>
        </el-col>
        <!-- 楼层选择 -->


        <el-col :span="12">
            <el-form-item label="设备类型" prop="categoryId"
                :rules="[
                  { required: true, message: '请选择设备类型', trigger: 'change' }
                 ]">
              <div class="select-with-icon">
                <el-select v-model="inputForm.categoryId" placeholder="请选择设备类型" style="width: calc(100% - 30px)" @change="handleCategoryChange">
                  <el-option
                    v-for="item in categoryList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <i class="el-icon-plus add-icon" @click="openCategoryForm"></i>
              </div>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate"
                :rules="[
                 ]">
              <el-date-picker
                v-model="inputForm.purchaseDate"
                type="date"
                placeholder="请选择采购日期"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="生产厂家" prop="manufacturerId"
                :rules="[
                  { required: true, message: '请选择生产厂家', trigger: 'change' }
                 ]">
              <div class="select-with-icon">
                <el-select v-model="inputForm.manufacturerId" placeholder="请选择生产厂家" style="width: calc(100% - 30px)" @change="handleManufacturerChange" :disabled="!inputForm.categoryId">
                  <el-option
                    v-for="item in manufacturerList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
                <i class="el-icon-plus add-icon" @click="openManufacturerForm"></i>
              </div>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="启用日期" prop="startDate"
                :rules="[
                 ]">
              <el-date-picker
                v-model="inputForm.startDate"
                type="date"
                placeholder="请选择启用日期"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="设备品牌" prop="brandId"
                :rules="[
                  { required: true, message: '请选择设备品牌', trigger: 'change' }
                 ]">
              <div class="select-with-icon">
                <el-select v-model="inputForm.brandId" placeholder="请选择设备品牌" style="width: calc(100% - 30px)" @change="handleBrandChange" :disabled="!inputForm.categoryId">
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.brandName"
                    :value="item.id">
                  </el-option>
                </el-select>
                <i class="el-icon-plus add-icon" @click="openBrandForm"></i>
              </div>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="计量单位" prop="unit"
                :rules="[
                 ]">
              <el-input v-model="inputForm.unit" placeholder="请填写计量单位"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="设备型号" prop="modelId"
                :rules="[
                  { required: true, message: '请选择设备型号', trigger: 'change' }
                 ]">
              <div class="select-with-icon">
                <el-select v-model="inputForm.modelId" placeholder="请选择设备型号" style="width: calc(100% - 30px)" :disabled="!inputForm.brandId">
                  <el-option
                    v-for="item in modelList"
                    :key="item.id"
                    :label="item.name + '（' + item.spec + '）'"
                    :value="item.id">
                  </el-option>
                </el-select>
                <i class="el-icon-plus add-icon" @click="openModelForm"></i>
              </div>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="固定资产编号" prop="assetCode"
                :rules="[
                 ]">
              <el-input v-model="inputForm.assetCode" placeholder="请填写固定资产编号"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="出厂编号/钢印" prop="serialNumber"
                :rules="[
                 ]">
              <el-input v-model="inputForm.serialNumber" placeholder="请填写出厂编号/钢印"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="维保单位" prop="maintenacer"
                :rules="[
                 ]">
              <el-input v-model="inputForm.maintenacer" placeholder="请填写维保单位"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="联系电话" prop="contactId"
                :rules="[
                 ]">
              <el-input v-model="inputForm.contactId" placeholder="请填写联系电话"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="设备状态" prop="status"
                :rules="[
                  { required: true, message: '请选择设备状态', trigger: 'change' }
                 ]">
              <el-select v-model="inputForm.status" placeholder="请选择设备状态" style="width: 100%">
                <el-option
                  v-for="item in $dictUtils.getDictList('device_status')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="楼层" prop="floorId" :rules="[{ required: true, message: '楼层不能为空', trigger: 'blur' }]">
            <SelectTree ref="floor"
                        :props="{ value: 'id', label: 'showName', children: 'childNodes' }"
                        url="/smis/floor/jfFloor/treeData"
                        :value="inputForm.floorId"
                        :clearable="true"
                        :accordion="true"
                        @getValue="(value) => { inputForm.floorId=value; $refs.selectPoint.showFloor(value); }" />
          </el-form-item>
        </el-col>
        <!-- 地图选点 -->
        <el-col :span="24" style="height: 400px;">
          <el-form-item label="所在位置" prop="x" :rules="[{ required: true, message:'请选择所在位置', trigger:'blur' }]">
            <select-point ref="selectPoint" @onMapClick="mapClick"></select-point>
          </el-form-item>
        </el-col>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  import EquipmentCategoryForm from './EquipmentCategoryForm'
  import ManufacturerForm from './ManufacturerForm'
  import DeviceBrandForm from './DeviceBrandForm'
  import EquipmentModelForm from './EquipmentModelForm'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import SelectPoint from '@/components/jfMap/selectPoint.vue'

  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        categoryList: [],
        manufacturerList: [],
        brandList: [],
        modelList: [],
        categoryFormVisible: false,
        manufacturerFormVisible: false,
        brandFormVisible: false,
        modelFormVisible: false,
        inputForm: {
          id: '',
          name: '',
          code: '',
          categoryId: '',
          locationId: '',
          purchaseDate: '',
          startDate: '',
          unit: '',
          manufacturerId: '',
          brandId: '',
          modelId: '',
          assetCode: '',
          serialNumber: '',
          maintenacer: '',
          contactId: '',
          status: '',
          floorId: '',
          x: '',
          y: '',
          z: ''
        }
      }
    },
    components: {
      EquipmentCategoryForm,
      ManufacturerForm,
      DeviceBrandForm,
      EquipmentModelForm,
      SelectTree,
      SelectPoint
    },
    created() {
      this.loadCategories();
    },
    watch: {
      'inputForm.floorId'(val) {
        this.$refs.selectPoint && this.$refs.selectPoint.showFloor(val);
        if (val && this.inputForm.x && this.inputForm.y) {
          this.$refs.selectPoint.setMarkPoint(val, this.inputForm.x, this.inputForm.y, this.inputForm.z, true);
        }
      }
    },
    methods: {
      loadManufacturers(categoryId) {
        this.$http({
          url: '/device/manufacturer/list',
          method: 'get',
          params: {
            categoryId: categoryId
          }
        }).then(({data}) => {
          if (data && data.code === 200) {
            this.manufacturerList = data.page && data.page.list ? data.page.list : []
          } else {
            this.manufacturerList = []
          }
        }).catch(() => {
          this.manufacturerList = []
        })
      },
      loadCategories() {
        this.$http({
          url: '/device/equipmentCategory/list',
          method: 'get'
        }).then(({data}) => {
          this.categoryList = (data.page && data.page.list) ? data.page.list.map(item => ({
            value: item.id,
            label: item.name
          })) : [];
        });
      },
      handleCategoryChange(categoryId) {
        this.inputForm.manufacturerId = '';
        this.inputForm.brandId = '';
        this.inputForm.modelId = '';
        this.manufacturerList = [];
        this.brandList = [];
        this.modelList = [];
        if (categoryId) {
          this.loadManufacturers(categoryId);
        }
      },
      loadBrands(manufacturerId) {
        this.$http({
          url: '/device/deviceBrand/list',
          method: 'get',
          params: { manufacturerId }
        }).then(({data}) => {
          if (data && data.code === 200) {
            this.brandList = (data.page && data.page.list) ? data.page.list : [];
          } else {
            this.brandList = [];
          }
        }).catch(() => {
          this.brandList = [];
        });
      },
      handleManufacturerChange(manufacturerId) {
        this.inputForm.brandId = '';
        this.inputForm.modelId = '';
        this.brandList = [];
        this.modelList = [];
        if (manufacturerId) {
          this.loadBrands(manufacturerId);
        }
      },
      handleBrandChange(brandId) {
        this.inputForm.modelId = '';
        this.modelList = [];
        if (brandId) {
          this.loadModels(brandId);
        }
      },
      loadModels(brandId) {
        this.$http({
          url: '/device/equipmentModel/list',
          method: 'get',
          params: { brandId }
        }).then(({data}) => {
          if (data && data.code === 200) {
            this.modelList = (data.page && data.page.list) ? data.page.list : [];
          } else {
            this.modelList = [];
          }
        }).catch(() => {
          this.modelList = [];
        });
      },
      init (method, id) {
        this.method = method
        this.inputForm.id = id
        if (method === 'add') {
          this.title = `新建设备管理`
          this.loadCategories()
          // 设置默认日期为当天
          const today = new Date()
          const year = today.getFullYear()
          const month = String(today.getMonth() + 1).padStart(2, '0')
          const day = String(today.getDate()).padStart(2, '0')
          this.inputForm.purchaseDate = `${year}-${month}-${day}`
          this.inputForm.startDate = `${year}-${month}-${day}`
        } else if (method === 'edit') {
          this.title = '修改设备管理'
          this.loadCategories()
        } else if (method === 'view') {
          this.title = '查看设备管理'
          this.loadCategories()
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/device/equipment/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data.equipment)
              // 手动触发级联加载
              if (this.inputForm.categoryId) {
                this.loadManufacturers(this.inputForm.categoryId)
                if (this.inputForm.manufacturerId) {
                  this.loadBrands(this.inputForm.manufacturerId)
                  if (this.inputForm.brandId) {
                    this.loadModels(this.inputForm.brandId)
                  }
                }
              }
              this.loading = false
            })
          }
        })
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/device/equipment/save`,
              method: 'post',
              data: this.inputForm
            }).then(({data}) => {
              if (data && data.success) {
                this.visible = false
                this.$message.success(data.msg)
                this.$emit('refreshDataList')
              }
              this.loading = false
            })
          }
        })
      },
      // 打开设备类型新增表单
      openCategoryForm() {
        this.$nextTick(() => {
          this.$refs.categoryForm.init('add')
          this.categoryFormVisible = true
        })
      },
      // 打开生产厂家新增表单
      openManufacturerForm() {
        this.$nextTick(() => {
          this.$refs.manufacturerForm.init('add', this.inputForm.categoryId)
          this.manufacturerFormVisible = true
        })
      },
      // 打开设备品牌新增表单
      openBrandForm() {
        this.$nextTick(() => {
          this.$refs.brandForm.init('add', this.inputForm.manufacturerId)
          this.brandFormVisible = true
        })
      },
      // 打开设备型号新增表单
      openModelForm() {
        this.$nextTick(() => {
          this.$refs.modelForm.init('add', this.inputForm.brandId)
          this.modelFormVisible = true
        })
      },
      // 设备类型新增完成后刷新列表
      handleCategoryAdded() {
        this.loadCategories()
      },
      // 生产厂家新增完成后刷新列表
      handleManufacturerAdded() {
        if (this.inputForm.categoryId) {
          this.loadManufacturers(this.inputForm.categoryId)
        }
      },
      // 设备品牌新增完成后刷新列表
      handleBrandAdded() {
        if (this.inputForm.manufacturerId) {
          this.loadBrands(this.inputForm.manufacturerId)
        }
      },
      // 设备型号新增完成后刷新列表
      handleModelAdded() {
        if (this.inputForm.brandId) {
          this.loadModels(this.inputForm.brandId)
        }
      },
      mapClick(e) {
        this.inputForm.x = e.x.toFixed(2)
        this.inputForm.y = e.y.toFixed(2)
        this.inputForm.z = e.z.toFixed(2)
      }
    }
  }
</script>

<style scoped>
.select-with-icon {
  display: flex;
  align-items: center;
}
.add-icon {
  margin-left: 5px;
  font-size: 20px;
  color: #409EFF;
  cursor: pointer;
  position: relative;
  z-index: 3000; /* 确保图标在最上层 */
}
</style>
